//common.js   公有的js
jQuery.support.cors = true;

//========跨域通信========
//获取登录页面
var thisLoginUrl;
//获取导航文本
var thisNavText;
//扩展导航文本
var thisExtendNavText;
//接收消息
if(window.top != window.self) {
	window.addEventListener('message',function(e){
	//	thisExtendNavText = $.getUrlData("modelName");
		var data = e.data;
		data = eval(data);
		if(data && data.navText) {
			thisNavText = data.navText + ((thisExtendNavText && thisExtendNavText != '') ? (">" + thisExtendNavText) : '');
		}
		if(data && data.loginUrl) {
			thisLoginUrl = data.loginUrl;
		}
		if(!thisLoginUrl || thisLoginUrl == '') {
			thisLoginUrl = parent.thisLoginUrl;
		}
		setNavText();
	}, false);
	window.top.postMessage(true, "*");
} else {
	window.addEventListener('message',function(e){
		var data = e.data;
		if(data === true) {
			sendMessage();
		}
	}, false);
}

//发送消息
function sendMessage() {
	if(navText && navText != '') {
		var data = {navText:navText, loginUrl:loginUrl};
		window.frames['J_iframe'].postMessage(data,'*');
	}
}

//导航栏赋值
function setNavText() {
	//导航文本
	var $iboxtitleSpan = $('.iboxtitle span');
	if($iboxtitleSpan && $iboxtitleSpan.length > 0){
		if(thisNavText && thisNavText != '') {
			var titleSpanHtml = $('.iboxtitle span').html();
			if(titleSpanHtml && titleSpanHtml != '') {
				var end = titleSpanHtml.lastIndexOf('</i>');
				if(end > 0) {
					titleSpanHtml = titleSpanHtml.substring(0,end+4);
					$('.iboxtitle span').html(titleSpanHtml + thisNavText);
				}
			}
		}
	}
}

//ajax异步
var ajaxAsync = true;
//ajax缓存
var ajaxCache = true;
//ajax超时时间
var ajaxTimeOut = 60000;


(function($){
	
		jQuery.addMask = function(options)
		{
			//var defaluts = {};
			//var opts = $.extend(defaluts, options);
			//waitingDialog.show();
		}
		
		jQuery.removeMask = function(options)
		{
			//waitingDialog.hide();
		}
		
		$.fn.showDatas =function(options)
		{
			alert(JSON.stringify(options.datas));
		}

		/**
	     * ajax封装
	     * url 发送请求的地址
	     * data 发送到服务器的数据，数组存储，如：{"date": new Date().getTime(), "state": 1}
	     * async 默认值: true。默认设置下，所有请求均为异步请求。如果需要发送同步请求，请将此选项设置为 false。
	     *       注意，同步请求将锁住浏览器，用户其它操作必须等待请求完成才可以执行。
	     * type 请求方式("POST" 或 "GET")， 默认为 "GET"
	     * dataType 预期服务器返回的数据类型，常用的如：xml、html、json、text
	     * successfn 成功回调函数
	     * errorfn 失败回调函数
	     */
		jQuery.dpAjax = function(options) 
		{
			var defaluts = 
			{
				type:"post",
				show:true,
				dataType : "json",
				async : ajaxAsync,
				cache : ajaxCache,
				timeout : ajaxTimeOut,
				success: function(){}
			};
			
			
			var opts = $.extend(defaluts, options);
			var error = opts.error || function(XMLHttpRequest, textStatus, errorThrown){
				  if(console)
				  {
					  console.info("error:" + XMLHttpRequest.responseText);
				  }
				  waitingDialog.hide();
	        };
	          
	        if(options.async == false) 
	        {
	        	 ajaxAsync = false;
	        }
	        
	        var openIndex;
			var currentAjax = $.ajax({ 
	        	  url:opts.url,
				  type : opts.type,
				  dataType : opts.dataType,
				  async : ajaxAsync,
				  cache : ajaxCache,
				  timeout : ajaxTimeOut,
				  data:opts.data,
				  success:function(datas){
					  if(opts.busiReturn) {
						  opts.busiReturn(datas);
					  }
					  if(datas.flag == "100100") {
						  opts.success(datas);
					  } else if(datas.flag == '100802') {
						  top.location.href = thisLoginUrl;
					  } else {
						  layer.msg(datas.message, {icon: 2});
					  }
				  },
				  error: error,
		          beforeSend : function (XMLHttpRequest){	
		        	  if(opts.show)
		        	  {
		        		openIndex = layer.alert('正在执行，请稍后......', {
		     	        	 skin: 'layui-layer-molv',
		     	        	 closeBtn: 0,
		     	        	 move  :true,
		     	        	 title:'碟普科技提示信息'
		     	        });
		     	        $('.layui-layer-btn').hide();
		        	  }
				  },complete : function (XMLHttpRequest, textStatus) {	
					  if(opts.complete) {
						  opts.complete();
					  }
					  if(opts.show)
					  {
						  if(openIndex)
						  {
							  layer.close(openIndex); 
						  }
					  }
				  }
			 });
			return currentAjax;
	    };
	    
	    jQuery.isEmpty = function(options) 
		{
	    	var defaluts = {
	    			type:"",
	    			id:"",
	    			field:"",
	    			msg:""
	    	};
			var opts = $.extend(defaluts, options);
			
			if(opts.type == "tips")
			{
				if(opts.field == "" || null == opts.field || opts.field.length == 0 || opts.field.trim() == undefined)
				{
					layer.tips(opts.msg, '#'+opts.id, {
		      		  tips: [1, '#3595CC'],
		      		  time: 4000
		      		});
					
					return false;
				}
				return true;
			}
			
			if(opts.field == "" || null == opts.field || opts.field.length == 0 || opts.field.trim() == undefined)
			{
				return false;
			}
			return true;
		};
		
		jQuery.getUrlData = function(name) 
		{
	      var url = location.href;
	      var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
	      if (reg.test(url)) return decodeURIComponent(RegExp.$2.replace(/\+/g, " "));
	      return "";
	   }
	    
})(jQuery);

String.prototype.endWith = function(s) {
	if (s == null || s == "" || this.length == 0 || s.length > this.length)
		return false;
	if (this.substring(this.length - s.length) == s)
		return true;
	else
		return false;
	return true;
}

String.prototype.startWith = function(s) {
	if (s == null || s == "" || this.length == 0 || s.length > this.length)
		return false;
	if (this.substr(0, s.length) == s)
		return true;
	else
		return false;
	return true;
}
/**
 * 日期格式化
 */
Date.prototype.format = function(fmt) {
    var o = {
        "M+" : this.getMonth() + 1,
        "d+" : this.getDate(),
        "h+" : this.getHours(),
        "m+" : this.getMinutes(),
        "s+" : this.getSeconds(),
        "q+" : Math.floor((this.getMonth() + 3) / 3),
        "S" : this.getMilliseconds()
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

/**
 * 两位小数点
 */
function showNumber(a,scale){
	a = a || 0;
	scale = scale || 2;
	return a.toFixed(scale);
}

/**
 * 精度截取
 */
function showScaleNumber(a,scale){
	a = a || 0;
	scale = scale || 2;
	return a.toFixed(scale);
}

/**
 * 单位为万
 */
function showBigNumber(a){
	a = a || 0.00;
	return (a / 10000).toFixed(2);
}

//时间格式：yyyy-MM-dd HH:mm:ss
function formateTime(time){
	if(time && time != ''){
		return time.substring(0, time.lastIndexOf(":"));
	} else {
		return '-';
	}
}
//时间格式：yyyy-MM-dd HH:mm:ss
function formateDate(time){
	if(time && time != ''){
		return time.split(' ')[0];
	} else {
		return '-';
	}
}

/**
 * 精确到分
 */
function formateToMinutes(sDate1){
	if(!sDate1 || sDate1 == ''){
		return '-';
	}
	var aDate  =  sDate1.split(":");
	return aDate[0] + ":" + aDate[1];
}

/**
 * 精确到日
 */
function formateToDate(sDate1, empty){
	if(!sDate1 || sDate1 == ''){
		return empty ? '' : '-';
	}
	var aDate  =  sDate1.split(" ");
	return aDate[0];
}

/**
 * 精确到月
 */
function formateToMonth(sDate1){
	if(!sDate1 || sDate1 == ''){
		return '';
	}
	var aDate  =  sDate1.split("-");
	return aDate[0]+"-"+aDate[1];
}


/**
 * 精确到年（获取年）
 */
function formateToYear(sDate1){
	if(!sDate1 || sDate1 == ''){
		return '';
	}
	var aDate  =  sDate1.split("-");
	return aDate[0];
}

/**
 * 获取月
 */
function getMonth(sDate1){
	if(!sDate1 || sDate1 == ''){
		return '';
	}
	var aDate  =  sDate1.split("-");
	return aDate[1];
}

/**
 * 时间格式：Integer
 */
function formateIntegerTime(a, fmt){
	fmt = fmt || 'yyyy-MM-dd hh:mm:ss';
	if(a && a != ''){
	 	var date = new Date(a * 1000);
	 	return date.format(fmt);
	 } else {
		 return '-';
	 }
}

/**
 * 时间格式：Integer
 */
function formateIntegerDate(a, fmt){
	fmt = fmt || 'yyyy-MM-dd';
	if(a && a != ''){
	 	var date = new Date(a * 1000);
	 	return date.format(fmt);
	 } else {
		 return '-';
	 }
}

/**
 * 时间格式：Integer
 */
function formateIntegerMinutes(a, fmt){
	fmt = fmt || 'yyyy-MM-dd hh:mm';
	if(a && a != ''){
	 	var date = new Date(a * 1000);
	 	return date.format(fmt);
	 } else {
		 return '-';
	 }
}

/*uuid*/
function guid() {
 	  function S4() {
 	    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
 	  }
 	  return S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4();
}

//计算天数差的函数，通用  
function dateDiff(sDate1){
    var  aDate,  oDate1,  iDays  
    aDate  =  sDate1.split("-")  
    oDate1  =  new  Date(aDate[1]  +  '-'  +  aDate[2].split(" ")[0]  +  '-'  +  aDate[0]) //转换为12-18-2006格式  
    
    sDate2  =  new  Date(); 
    var year2 = sDate2.getFullYear();
    var month2 = sDate2.getMonth() + 1;
    var day2 = sDate2.getDate();
    var oDate2 = new  Date(month2 + '-' + day2 + '-' + year2 );
    
    var diffDate = (oDate1  -  oDate2)  /  1000  /  60  /  60  /24;//把相差的毫秒数转换为天数  
    var iDays  =  parseInt(diffDate);
    if(iDays > 0){
    	return iDays;
    } else if(iDays < 0){
    	return '<span style="color:red;">已超期'+  Math.abs(iDays) + '天</span>';
    } else {
    	return '<span style="color:red;">今日到期</span>';
    }
} 

/**
 * 默认30天 
 */
$('#buttonall').on('click', '.btn', function(e){
    $('#buttonall .btn').removeClass('butactive');
    $(e.target).addClass('butactive');
});

$('.navul').on('click', 'li', function(e){
    $('.navul li').removeClass('navulactive');
    $(e.target).addClass('navulactive');
});

/**
 * 派单选项卡
 */
jQuery(function(){
	var $ul = $('#send-tab>ul li');
	var $div = $('#send-content .send-div');
	$ul.click(function(){
		var $this = $(this);
		var $t = $this.index();
		$thisIndex = $t;
		$ul.removeClass();
		$this.addClass('send-active');
		$this.find("i").addClass('fa fa-dot-circle-o');
		$this.siblings().find("i").removeClass('fa fa-dot-circle-o').addClass('fa fa-circle-o');
		$div.css('display','none');
		$("#table_list_1").setGridWidth($(window).width()-100);
		$div.eq($t).css('display','block');
	});	 
})

/**
 * 过滤HTML标签
 */
String.prototype.stripHTML = function() {
    var reTag = /<(?:.|\s)*?>/g;
    return this.replace(reTag,"");
}

function toUpperCase(obj)
{
 	obj.value = obj.value.toUpperCase()
}
 

/**
 * 必填来个红色
 */
$("input,textarea").each(function(){
  var placeholdertxt =  $(this).attr("placeholder");
  if(placeholdertxt && placeholdertxt != ""){
	  if(placeholdertxt.indexOf("必填") >= 0 ) { 
		  $(this).addClass("colorred");
		} 
  	}
});

	